package org.example.domain.strategy.service.rule.chain.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.armory.IStrategyDispatch;
import org.example.domain.strategy.service.rule.chain.AbstractLogicChain;
import org.example.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import org.example.types.common.Constants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Component("rule_weight")
public class RuleWeightogicChain extends AbstractLogicChain {
    @Resource
    private IStrategyRepository repository;
    @Resource
    private IStrategyDispatch strategyDispatch;
    private String ruleModel = DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("规则责任链-权重 userId:{} strategyId:{} ruleModel:{}", userId,strategyId);

        //查询规则配置
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel);
        Map<Long, String> analyticalValue = getAnalyticalValue(ruleValue);
        Set<Long> keySet = analyticalValue.keySet();
        List<Long> keylist = new ArrayList<>(keySet);
        Collections.sort(keylist);
        Integer userScore = repository.queryActivityAccountUseCount(userId,strategyId);
        Long nextValue =  keylist.stream().filter(key->key <=userScore)
                .max(Long::compareTo)
                .orElse(null);
         if (null != nextValue) {
             log.info("规则责任链-权重接管 userId:{} strategyId:{} ruleModel:{} ", userId,strategyId,ruleModel);
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .logicModel(DefaultChainFactory.LogicModel.RULE_WEIGHT)
                    .awardId(strategyDispatch.getRandomAwardId(strategyId,analyticalValue.get(nextValue)))
                    .build();
        }
             log.info("规则责任链-权重放行 userId:{} strategyId:{} ruleModel:{} ", userId,strategyId,ruleModel);

        return next().logic(userId,strategyId);
    }
    private Map<Long, String> getAnalyticalValue(String ruleValue){
        Map<Long,String> ValueMap = new HashMap<>();
        String[] splitRuleValues = ruleValue.split(Constants.SPACE);
       for (String splitRuleValue : splitRuleValues) {
           String[] RuleValue = splitRuleValue.split(":");
           if (RuleValue.length != 2){
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + RuleValue);
           }
           ValueMap.put(Long.parseLong(RuleValue[0]),splitRuleValue);
       }
        return ValueMap;
    }
}
